import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from sklearn.linear_model import LinearRegression
from scipy.stats import linregress

# 设置全局字体为支持中文的字体(如 SimHei、Microsoft YaHei)
plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows 系统常用字体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

# 示例数据
data = {
    'Y_std_left': [41.548, 42.206, 40.993, 39.897, 39.795, 37.395, 35.632],
    'Y_std_right': [45.8649, 46.5096, 44.8136, 45.2847, 43.7538, 44.1237, 40.4534],
    'pwm': ['100%', '80%', '47%', '30%', '15%', '20%', '10%'],
    'sensor1': [45, 46, 49, 53, 55, 58, 71],
    'sensor2': [38, 39, 42, 45, 45, 50, 62]
}

df = pd.DataFrame(data)

# 方法1：使用scipy.stats.linregress计算线性回归
print("=" * 60)
print("线性拟合结果")
print("=" * 60)

# 拟合Y_std_left vs sensor1
slope_left, intercept_left, r_value_left, p_value_left, std_err_left = linregress(df['sensor1'], df['Y_std_left'])

# 拟合Y_std_right vs sensor2
slope_right, intercept_right, r_value_right, p_value_right, std_err_right = linregress(df['sensor2'], df['Y_std_right'])

# 打印直线方程
print(f"Y_std_left 拟合直线方程:")
print(f"Y = {slope_left:.4f} * X + {intercept_left:.4f}")
print(f"斜率: {slope_left:.4f}")
print(f"截距: {intercept_left:.4f}")
print(f"相关系数 R: {r_value_left:.4f}")
print(f"决定系数 R²: {r_value_left**2:.4f}")
print(f"标准误差: {std_err_left:.4f}")
print()

print(f"Y_std_right 拟合直线方程:")
print(f"Y = {slope_right:.4f} * X + {intercept_right:.4f}")
print(f"斜率: {slope_right:.4f}")
print(f"截距: {intercept_right:.4f}")
print(f"相关系数 R: {r_value_right:.4f}")
print(f"决定系数 R²: {r_value_right**2:.4f}")
print(f"标准误差: {std_err_right:.4f}")
print()

# 为每个sensor创建独立的插值范围
sensor1_range = np.linspace(min(df['sensor1']), max(df['sensor1']), 100)
sensor2_range = np.linspace(min(df['sensor2']), max(df['sensor2']), 100)

# 计算拟合直线的预测值
y_pred_left = slope_left * sensor1_range + intercept_left
y_pred_right = slope_right * sensor2_range + intercept_right

# 为插值创建函数
f_left = interpolate.interp1d(df['sensor1'], df['Y_std_left'], 
                             kind='linear', fill_value='extrapolate')
f_right = interpolate.interp1d(df['sensor2'], df['Y_std_right'], 
                              kind='linear', fill_value='extrapolate')

# 在各自的sensor范围内应用插值函数
Y_std_left_interpolation = f_left(sensor1_range)
Y_std_right_interpolation = f_right(sensor2_range)

# 创建图表
plt.figure(figsize=(14, 8))

# 绘制原始数据点
plt.scatter(df['sensor1'], df['Y_std_left'], color='blue', marker='o', s=100,
           label='Y_std_left (原始数据)', zorder=5)
plt.scatter(df['sensor2'], df['Y_std_right'], color='red', marker='s', s=100,
           label='Y_std_right (原始数据)', zorder=5)

# 绘制插值后的曲线
plt.plot(sensor1_range, Y_std_left_interpolation, 'b--', linewidth=2, alpha=0.7,
         label='Y_std_left (插值)')
plt.plot(sensor2_range, Y_std_right_interpolation, 'r--', linewidth=2, alpha=0.7,
         label='Y_std_right (插值)')


print(f"Y = {slope_right:.4f} * X + {intercept_right:.4f}")

# 绘制拟合直线
plt.plot(sensor1_range, y_pred_left, 'b-', linewidth=3,
         label=f'Y_std_left 拟合直线 (Y = {slope_left:.4f} * X + {intercept_left:.4f})')
plt.plot(sensor2_range, y_pred_right, 'r-', linewidth=3,
         label=f'Y_std_right 拟合直线 (Y = {slope_right:.4f} * X + {intercept_right:.4f})')

# 添加标题和标签
plt.title('对比度随温度变化曲线', fontsize=16)
plt.xlabel('温度', fontsize=14)
plt.ylabel('对比度', fontsize=14)
plt.legend(fontsize=12, loc='best')

# 添加网格
plt.grid(True, linestyle='--', alpha=0.7)

# 显示图表
plt.tight_layout()
plt.show()

# 计算拟合优度
def calculate_r_squared(y_actual, y_predicted):
    ss_res = np.sum((y_actual - y_predicted) ** 2)
    ss_tot = np.sum((y_actual - np.mean(y_actual)) ** 2)
    return 1 - (ss_res / ss_tot)

# 计算原始数据点的拟合优度
y_pred_left_original = slope_left * df['sensor1'] + intercept_left
y_pred_right_original = slope_right * df['sensor2'] + intercept_right

r2_left = calculate_r_squared(df['Y_std_left'], y_pred_left_original)
r2_right = calculate_r_squared(df['Y_std_right'], y_pred_right_original)

print("=" * 60)
print("拟合质量评估")
print("=" * 60)
print(f"Y_std_left 拟合优度 R²: {r2_left:.4f}")
print(f"Y_std_right 拟合优度 R²: {r2_right:.4f}")

# 打印一些统计信息
print("\n" + "=" * 60)
print("数据范围统计")
print("=" * 60)
print(f"Sensor1值范围: {min(df['sensor1'])} 到 {max(df['sensor1'])}")
print(f"Sensor2值范围: {min(df['sensor2'])} 到 {max(df['sensor2'])}")
print(f"Y_std_left范围: {min(df['Y_std_left']):.2f} 到 {max(df['Y_std_left']):.2f}")
print(f"Y_std_right范围: {min(df['Y_std_right']):.2f} 到 {max(df['Y_std_right']):.2f}")
